package com.zbiti.anvil.job.executor.holder;

import com.zbiti.module.system.base.api.domain.SysUserDomain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * @author tangxy
 * @version 1.0
 * @date 2024/8/29
 * @description 用户对象会话承载器
 */
public class ThreadLocalSessionHolder {

    // 日志记录器
    private static final Logger logger = LoggerFactory.getLogger(ThreadLocalSessionHolder.class);

    /**
     * 保存用户对象
     */
    private static final ThreadLocal<SysUserDomain> USER_DOMAIN_THREAD_LOCAL = new ThreadLocal<>();

    // 禁止外部构造
    private ThreadLocalSessionHolder() {
    }

    /**
     * 设置用户对象
     *
     * @param sysUserDomain 用户对象
     */
    public static void setUserDomainThreadLocal(SysUserDomain sysUserDomain) {
        logger.info("***** ==================== {} Start ====================*****", "ThreadLocalSessionHolder");
        logger.info("***** SysUserDomain对象承载器 - 注入用户对象：{}", sysUserDomain == null ? "null" : sysUserDomain.getClass().getName());

        USER_DOMAIN_THREAD_LOCAL.set(sysUserDomain);

        logger.info("*****==================== {} End ====================*****", "ThreadLocalSessionHolder");
    }

    /**
     * 获得用户对象
     *
     * @return 用户对象
     */
    public static Optional<SysUserDomain> getUserDomainThreadLocal() {
        return Optional.ofNullable(USER_DOMAIN_THREAD_LOCAL.get());
    }

    /**
     * 清除用户对象
     */
    public static void clearUserDomainThreadLocal() {
        USER_DOMAIN_THREAD_LOCAL.remove();
    }
}
